import { useEffect, useState } from "react";
import { useHistory } from "react-router-dom";
import { Nav } from "@/components/func";

/* 基础信息 */
import QrName from "./component/baseMessage/qr_name";
import QrGroup from "./component/baseMessage/qr_group";
import QrUser from "./component/baseMessage/kefu_user";
import QrStaffLimit from "./component/baseMessage/staff_limit";
import QrOnOffSpare from "./component/baseMessage/onOff_spare";
import QrCustomerTag from "./component/baseMessage/customer_tag";
import QrCustomerNote from "./component/baseMessage/customer_note";
import QrCustomerDesc from "./component/baseMessage/customer_desc";

/* 欢迎语 */
import WelcomeType from "./component/welcomeMessage/type_message";
import WelcomeSet from "./component/welcomeMessage/set_message";
import WelcomeSetTime from "./component/welcomeMessage/time_set_message";
import WelcomeMesClose from "./component/welcomeMessage/close_message";

/* 功能 */
import FuncAutoAdd from "./component/func/auto_add";
import FuncQrView from "./component/func/qr_view";
import { createQr, getQrId } from "@/assets/js/networkRequest/method";
import "./index.less";

let operaType = "";

/* 对客服人员数据进行处理 */
const changeKf = (userData: any, LimitData: any, isLimit: boolean): any => {
  let kfUserData = [];
  const { type } = userData;
  if (type === 1) {
    kfUserData = userData.user;
  } else {
    const { workCycles } = userData;
    workCycles.map((item: any) => {
      kfUserData.push(...item.user);
    });
  }
  console.log(kfUserData);

  /* 没有限制的客服 */
  kfUserData = kfUserData.map((item: any) => ({
    userid: item.userid,
    day_add_user_limit: 0,
  }));

  /* 有限制的客服 */
  let kfLimitData = LimitData.map((item: any) => ({
    userid: item.userid,
    day_add_user_limit: item.limit,
  }));

  let staffs: any = isLimit ? kfLimitData : kfUserData;
  return {
    schedule_enable: type === 1 ? false : true,
    staffs,
    day_add_user_limit_enable: isLimit,
  };
};
/* 欢迎语设置类型转换 */
const auto_reply_rule = (value: any) => {
  return {
    auto_reply_rule: value === 1 ? "custom" : value === 2 ? "default" : "close",
  };
};

const QrCreate = (): JSX.Element => {
  let history: any = useHistory();
  /* 名称 */
  const [name, setName] = useState("");
  /* 分组id */
  const [qrGroupId, setQrGroupId] = useState(0);
  /* 上线类型 */
  const [userType, setUserType] = useState(1);
  /* 客服信息 */
  const [kfData, setKfData] = useState({});
  /* 是否添加上限 */
  const [isLimit, setIsLimit] = useState(false);
  /* 上限数量数据 */
  const [kfLimit, setKfLimit] = useState([]);
  /* 允许上下线 */
  const [allowManualOffline, setAllowManualOffline] = useState(false);
  /* 备用员工 */
  const [backupStaff, setBackupStaff]: any = useState(null);
  /* 客户标签 */
  const [customerTag, setCustomerTag] = useState([]);
  /* 客服备注 */
  const [customerNote, setCustomerNote] = useState("");
  /* 客户描述 */
  const [customerDesc, setCustomerDesc] = useState("");

  /* 欢迎语类型 */
  const [welcomeType, setWelcomeType] = useState(1);
  /* 欢迎语 */
  const [welcomMsg, setWelcomMsg] = useState({ text: { content: "" } });
  /* 是否分时段欢迎语 */
  const [cronWelcomeEnable, setCronWelcomeEnable] = useState(false);
  /* 欢迎语屏蔽列表 */
  const [welcomeCloseName, setWelcomeCloseName] = useState([]);
  /* 是否自动通过加好友 */
  const [skipVerify, setSkipVerify] = useState(false);
  /* 自动通过加好友 */
  const [atuoAgreeTime, setAtuoAgreeTime] = useState([]);

  // 根据id请求活码数据
  const getQrInit = async (id: number, callback: any) => {
    let res: any = await getQrId({ id });
    if (res.code === 200) {
      let { data } = res;
      setName(data.name);
      setQrGroupId(data.qr_group);
      setBackupStaff(data.backup_staff);
      callback(data);
    }
  };

  useEffect(() => {
    if (history.location.query) {
      let { type, id } = history.location.query;
      operaType = type;
      if (type === "update") {
        getQrInit(id, (data: any) => {
          console.log(data);
        });
      } else if (type === "copy") {
        getQrInit(id, (data: any) => {
          console.log(data);
        });
      }
    }
  }, []);

  return (
    <div className="qr-create w-full h-full flex flex-col">
      <Nav name="新建活码" router="/qr" />
      <section className="scrollY w-full bg-grey-100 flex-1 overflow-y-auto p-16">
        <div className="bg-white p-24 relative">
          <Title name="基础信息" />
          {/* 二维码名称 */}
          <QrName name={name} setName={setName} operaType={operaType} />
          {/* 选择分组 */}
          <QrGroup qrGroupId={qrGroupId} setQrGroupId={setQrGroupId} />
          {/* 客服人员 */}
          <QrUser userType={userType} setUserType={setUserType} setKfData={setKfData} />
          {/* 员工添加上限 */}
          <QrStaffLimit
            kfData={kfData}
            isLimit={isLimit}
            setIsLimit={setIsLimit}
            setKfLimit={setKfLimit}
          />
          {/* 允许员工上下线 */}
          <QrOnOffSpare
            allowManualOffline={allowManualOffline}
            setAllowManualOffline={setAllowManualOffline}
            backupStaff={backupStaff}
            setBackupStaff={setBackupStaff}
          />
          {/* 客户标签 */}
          <QrCustomerTag customerTag={customerTag} setCustomerTag={setCustomerTag} />
          {/* 客户备注 */}
          <QrCustomerNote customerNote={customerNote} setCustomerNote={setCustomerNote} />
          {/* 客户描述 */}
          <QrCustomerDesc customerDesc={customerDesc} setCustomerDesc={setCustomerDesc} />

          <Title name="设置欢迎语" />
          <div className="w-full h-full relative flex mt-24 justify-between pl-32 max-w-1230">
            <section className="message-left-content flex-1 felx flex-col mr-30">
              <WelcomeType welcomeType={welcomeType} setWelcomeType={setWelcomeType} />
              {/* 渠道欢迎语 */}
              <WelcomeSet
                welcomeType={welcomeType}
                welcomMsg={welcomMsg}
                setWelcomMsg={setWelcomMsg}
              />
              {/* 默认欢迎语 */}
              <div
                className={`h-20 relative w-full mt-24 ${
                  welcomeType === 2 ? "" : "none"
                }`}>
                <p className="absolute bottom-0 left-90 text-grey-400">
                  将发送成员已设置的欢迎语，若所选成员未设置欢迎语，则不会发送欢迎语
                </p>
              </div>
              {/* 不发送 */}
              <div className={`${welcomeType === 3 ? "" : "none"}`}></div>
            </section>
            <section className="w-280"></section>
          </div>
          {/* 分时段欢迎语 */}
          <WelcomeSetTime
            welcomeType={welcomeType}
            cronWelcomeEnable={cronWelcomeEnable}
            setCronWelcomeEnable={setCronWelcomeEnable}
          />
          {/* 欢迎语屏蔽 */}
          <WelcomeMesClose
            welcomeCloseName={welcomeCloseName}
            setWelcomeCloseName={setWelcomeCloseName}
          />

          <Title name="功能设置" classname="mt-46" />
          {/* 自动通过好友 */}
          <FuncAutoAdd
            atuoAgreeTime={atuoAgreeTime}
            skipVerify={skipVerify}
            setAtuoAgreeTime={setAtuoAgreeTime}
            setSkipVerify={setSkipVerify}
          />
          {/* 二维码预览 */}
          <FuncQrView />
          <button
            type="button"
            className="cursor-pointer w-140 h-40 bg-blue-default rounded-sm mt-8 mr-0 mb-16 ml-110 text-white"
            onClick={async () => {
              let backup_staff = {};
              if (backupStaff) {
                let { avatar, name, userid } = backupStaff;
                backup_staff = { avatar, name, userid };
              }
              let data = await createQr({
                name,
                qr_group: qrGroupId,
                ...changeKf(kfData, kfLimit, isLimit),
                allow_manual_offline: allowManualOffline,
                backup_staff: backup_staff,
                auto_mark_tags: customerTag,
                customer_remark: customerNote,
                customer_desc: customerDesc,
                ...auto_reply_rule(welcomeType),
                auto_reply: welcomMsg,
                cron_welcome_enable: cronWelcomeEnable,
                block_kw_list: welcomeCloseName,
                skip_verify: skipVerify,
                cron_skip_verify: atuoAgreeTime,
                scene: 2,
                type: 2,
                creator_staff: "NiuPengYuan",
              });
              console.log(data);

              console.log({
                name,
                qr_group_id: qrGroupId,
                ...changeKf(kfData, kfLimit, isLimit),
                allow_manual_offline: allowManualOffline,
                backup_staff: backupStaff,
                auto_mark_tags: customerTag,
                customer_remark: customerNote,
                customer_desc: customerDesc,
                ...auto_reply_rule(welcomeType),
                auto_reply: welcomMsg,
                cron_welcome_enable: cronWelcomeEnable,
                block_kw_list: welcomeCloseName,
                skip_verify: skipVerify,
                cron_skip_verify: atuoAgreeTime,
                scene: 2,
                type: 2,
                creator_staff: "NiuPengYuan",
              });
            }}>
            新建活码
          </button>
        </div>
      </section>
    </div>
  );
};

/* 标题 */
const Title = ({
  name,
  classname,
}: {
  name: string;
  classname?: string;
}): JSX.Element => (
  <h3
    className={` text-base h-34 mb-16 box-border border-b-1 border-solid border-grey-200 ${classname}`}>
    {name}
  </h3>
);

export default QrCreate;
